package com.sgl.retrofitdemo.net;

import com.orhanobut.logger.Logger;

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

/**
 * Created by sunqiyong on 2016/11/13.
 */

public class ApiService {
    private static final String API_BASE_URL = "";
    private static final String TEST_API_BASE_URL = "http://192.168.0.103:5000/";
    private Retrofit mRetrofit;
    private boolean isTest = true;

    private static class Holder {
        private static ApiService apiService = new ApiService();
    }

    public static ApiService getInstance() {
        return Holder.apiService;
    }

    private ApiService() {
        this(true);
    }

    public <T> T createApi(Class<T> clazz) {
        return this.mRetrofit.create(clazz);
    }

    private ApiService(boolean useRxJava){
        Retrofit.Builder mBuilder = new Retrofit.Builder();
        mBuilder.baseUrl(isTest ? TEST_API_BASE_URL : API_BASE_URL)
                .client(getClient())
                .addConverterFactory(FastJsonConvertFactory.create());
        if(useRxJava){
            mBuilder.addCallAdapterFactory(RxJavaCallAdapterFactory.create());
        }
        this.mRetrofit = mBuilder.build();
    }

    private OkHttpClient getClient() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        /**
         * setlevel用来设置日志打印的级别，共包含四个级别：NONE、BASIC、HEADER、BODY
         * BASIC: 请求/响应行       HEADER: 请求/响应行 + 头          BODY : 请求/响应行 + 头 + 体
         */
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        SSLSocketFactory sslSocketFactory = null;
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                        }

                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                        }

                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[0];
                        }
                    }
            };
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new SecureRandom());
            sslSocketFactory = sslContext.getSocketFactory();
        } catch (Exception e) {
            Logger.e(e.getMessage());
        }
        return new OkHttpClient.Builder()
                //.addInterceptor(new PublicInterceptor())//增加公共拦截器
                .addInterceptor(loggingInterceptor)
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .sslSocketFactory(sslSocketFactory)
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                })
                .build(); // cookie?
    }

}
